package com.inspur.edp.bef.bizentity.json.operation;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityErrorCodeEnum;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityException;
import com.inspur.edp.bef.bizentity.operation.internalmgraction.TccSettingElement;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;
import com.inspur.edp.das.commonmodel.json.CommonModelNames;

import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME;

public class TccSettingElementDeserializer extends JsonDeserializer<TccSettingElement> {

  @Override
  public final TccSettingElement deserialize(JsonParser jsonParser, DeserializationContext context){
     return deserializeTccSettingElement(jsonParser);
  }


  private TccSettingElement deserializeTccSettingElement(JsonParser jsonParser){
    TccSettingElement tccElement = createTccSettingElement();

    SerializerUtils.readStartObject(jsonParser);
    while (jsonParser.getCurrentToken() == FIELD_NAME) {
      String propName = SerializerUtils.readPropertyName(jsonParser);
      readPropertyValue(tccElement, propName, jsonParser);
    }
    SerializerUtils.readEndObject(jsonParser);
    if(tccElement.getTccAction().getCode()==null){
      tccElement.getTccAction().setCode(tccElement.getCode());
    }
    if(tccElement.getTccAction().getName()==null){
      tccElement.getTccAction().setName(tccElement.getName());
    }
    return tccElement;
  }

  private void readPropertyValue(TccSettingElement ele, String propName, JsonParser jsonParser) {
    switch (propName) {
      case CommonModelNames.ID:
        ele.setID(SerializerUtils.readPropertyValue_String(jsonParser));
        break;
      case CommonModelNames.Code:
        ele.setCode(SerializerUtils.readPropertyValue_String(jsonParser));
        break;
      case CommonModelNames.Name:
        ele.setName(SerializerUtils.readPropertyValue_String(jsonParser));
        break;
      case BizEntityJsonConst.TriggerFields:
        ele.setTriggerFields(SerializerUtils.readStringArray(jsonParser));
        break;
      case BizEntityJsonConst.TccAction:
        TccActionDeserializer deserializer = new TccActionDeserializer();
        ele.setTccAction(deserializer.deserialize(jsonParser,null));
        break;
      default:
        throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_BUSINESS_ENTITY_0064, "TccSettingElementDeserializer", propName);
    }
  }

  protected TccSettingElement createTccSettingElement() {
    return new TccSettingElement();
  }
}
